﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace Useful.GUI
{
    public class NotificationForm : Form
    {
        private LinkLabel lMessage = new LinkLabel();
        private Timer tAnimator = new Timer();

        private DateTime begin;
        private bool moving = true;
        private int NeedTop;

        private GuiHelper.ProcessActionDelegate Action;

        public NotificationForm(string msg, GuiHelper.ProcessActionDelegate action)
        {
            Action = action;

            Width = 200;
            Height = 100;
            TopMost = true;

            lMessage.Text = msg;

            this.Load += NotificationForm_Load;
            this.Shown += NotificationForm_Shown;
        }

        private void NotificationForm_Shown(object sender, EventArgs e)
        {
            try
            {
                begin = DateTime.Now;
                tAnimator.Start();
            }
            catch
            {
                Close();
            }
        }

        private void NotificationForm_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            this.ShowInTaskbar = false;

            lMessage.AutoSize = false;
            lMessage.Dock = DockStyle.Fill;
            lMessage.TextAlign = ContentAlignment.MiddleLeft;
            lMessage.Click += new EventHandler(lMessage_Click);
            this.Controls.Add(lMessage);

            Rectangle r = Screen.PrimaryScreen.WorkingArea;

            Left = r.Width - Width;
            Top = r.Height;
            NeedTop = r.Height - Height;

            tAnimator.Interval = 20;
            tAnimator.Tick += tAnimator_Tick;
        }

        private void lMessage_Click(object sender, EventArgs e)
        {
            if (Action != null)
                Action();
        }

        private void tAnimator_Tick(object sender, EventArgs e)
        {
            try
            {
                if ((DateTime.Now - begin).Seconds > 20 || Opacity < 0.05)
                    Close();
                else if (!moving)
                    Opacity -= 0.005;
                else if (Top > NeedTop)
                    Top -= 2;
                else
                    moving = false;
            }
            catch
            {
                Close();
            }
        }
    }
}
